package com.saltedfish.tool.util;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.res.Resources;
import android.os.Vibrator;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.ViewConfiguration;
import android.view.WindowManager;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class UIUtils {

    public static int m_screenWidth = 0;
    public static int m_screenHeight = 0;
    public static int m_screenRealWidth = 0;
    public static int m_screenRealHeight = 0;
    public static int m_dpi = 0;
    public static float m_resScale = 0;

    private static boolean m_init = true;
    public static int m_NavigationBarHeight = -1;

    /**
     * 初始化获取屏幕参数
     *
     * @param context
     * @return 成功/失败
     */
    public static boolean InitData(Context context) {
        boolean out = false;
        if (m_init) {
            if (context instanceof Activity) {
                m_init = false;

                Display display = ((Activity) context).getWindowManager().getDefaultDisplay();
                DisplayMetrics metrics = new DisplayMetrics();
                display.getMetrics(metrics);
                m_dpi = metrics.densityDpi;
                m_screenWidth = metrics.widthPixels;
                m_screenHeight = metrics.heightPixels;
                if (m_screenWidth > m_screenHeight) {
                    m_screenWidth += m_screenHeight;
                    m_screenHeight = m_screenWidth - m_screenHeight;
                    m_screenWidth -= m_screenHeight;
                }
                m_resScale = metrics.density;

                m_screenRealWidth = m_screenWidth;
                m_screenRealHeight = m_screenHeight;
                if (android.os.Build.VERSION.SDK_INT >= 17) {
                    try {
                        Method method = Display.class.getMethod("getRealMetrics", new Class[]{DisplayMetrics.class});
                        method.invoke(display, new Object[]{metrics});
                        m_screenRealWidth = metrics.widthPixels;
                        m_screenRealHeight = metrics.heightPixels;
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                }
                out = true;
            }
        } else {
            out = true;
        }
        return out;
    }



    /**
     * Display metrics display metrics.
     *
     * @param context the context
     * @return the display metrics
     */
    public static DisplayMetrics displayMetrics(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(dm);
        return dm;
    }

    /**
     * 设置手机震动模式
     * @param context
     */
    public static void setVibrator(Context context) {
        Vibrator vibrator = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE);
        vibrator.vibrate(1000);
    }

    public static int getScreenW() {
        return m_screenWidth;
    }

    public static int getScreenH() {
        return m_screenHeight;
    }

    /**
     * 素材以480x800屏幕为标准
     *
     * @param size
     * @return
     */
    public static int PxToDpi_hdpi(int size) {
        return (int) (size / 1.5f * m_resScale + 0.5f);
    }

    /**
     * @param size
     * @return
     * @deprecated use {@link #PxToDpi_hdpi(int)}
     */
    @Deprecated
    public static int PxToDpi(int size) {
        return PxToDpi_hdpi(size);
    }

    /**
     * 素材以720*1280屏幕为标准
     *
     * @param size
     * @return
     */
    public static int PxToDpi_xhdpi(int size) {
        return (int) (size / 2f * m_resScale + 0.5f);
    }

    /**
     * 素材以1080*1920屏幕为标准
     *
     * @param size
     * @return
     */
    public static int PxToDpi_xxhdpi(int size) {
        return (int) (size / 3f * m_resScale + 0.5f);
    }

    public static int getRealPixel_720P(int size) {
        return PxToDpi_xhdpi(size);
    }

    /**
     * 获取状态栏高度(顶部),即使全屏也能获取
     *
     * @param ac
     * @return
     */
    public static int GetStatusBarHeight2(Activity ac) {
        int out = 0;
        try {
            if (ac != null) {
                Class<?> c = Class.forName("com.android.internal.R$dimen");
                Object obj = c.newInstance();
                Field field = c.getField("status_bar_height");
                int x = Integer.parseInt(field.get(obj).toString());
                out = ac.getResources().getDimensionPixelSize(x);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return out;
    }

    /**
     * 获取当前状态栏高度(顶部),全屏状态下返回0
     *
     * @param ac
     * @return
     */
    public static int GetCurrentStatusBarHeight(Activity ac) {
        int out = 0;
        //非全屏,有状态栏
        if (ac != null && (ac.getWindow().getAttributes().flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) == 0) {
            out = GetStatusBarHeight2(ac);
        }
        return out;
    }

    /**
     * 获取NavigationBar的高度
     */
    public static int getNavigationBarHeight(Context context) {
        if (m_NavigationBarHeight == -1) {
            m_NavigationBarHeight = 0;
            Resources rs = context.getResources();
            int id = rs.getIdentifier("navigation_bar_height", "dimen", "android");
            if (id > 0 && checkDeviceHasNavigationBar(context)) {
                m_NavigationBarHeight = rs.getDimensionPixelSize(id);
            }
        }
        return m_NavigationBarHeight;
    }

    public static int getBottomKeyboardHeight(Activity activity){
        int screenHeight =  getAccurateScreenDpi(activity)[1];
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int heightDifference = screenHeight - dm.heightPixels;
        return heightDifference;
    }

    /**
     * 获取精确的屏幕大小
     */
    public static int[] getAccurateScreenDpi(Activity activity) {
        int[] screenWH = new int[2];
        Display display = activity.getWindowManager().getDefaultDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        try {
            Class<?> c = Class.forName("android.view.Display");
            Method method = c.getMethod("getRealMetrics",DisplayMetrics.class);
            method.invoke(display, dm);
            screenWH[0] = dm.widthPixels;
            screenWH[1] = dm.heightPixels;
        }catch(Exception e){
            e.printStackTrace();
        }
        return screenWH;
    }

    public static int getNavigationBarHeight2(Context context) {
        if (android.os.Build.VERSION.SDK_INT < 17) {
            return getNavigationBarHeight(context);
        }
        return 0;
    }

    /**
     * 判断是否存在NavigationBar
     *
     * @param context
     * @return
     */
    public static boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hasNavigationBar;
    }

    /**
     * 是否有物理Home键，返回true则有，否则为false
     */
    public static boolean hasPhysicalKey(Context context) {
        boolean hasPermanentMenuKey = false;
        if (android.os.Build.VERSION.SDK_INT >= 14) {
            ViewConfiguration vc = ViewConfiguration.get(context);
            try {
                Method m = ViewConfiguration.get(context).getClass().getMethod("hasPermanentMenuKey");
                hasPermanentMenuKey = (Boolean) m.invoke(vc);
            } catch (Throwable e) {
                e.printStackTrace();
                hasPermanentMenuKey = false;
            }
        }
        return hasPermanentMenuKey;
    }

    public static int getVirtualKeyHeight(Context context) {
        int virtualKeyHeight = m_screenRealHeight - m_screenHeight;
        if (virtualKeyHeight == 0 && android.os.Build.VERSION.SDK_INT < 17) {
            virtualKeyHeight = getNavigationBarHeight(context);
        }
        return virtualKeyHeight;
    }

    /**
     * 把dip单位转成px单位
     *
     * @param context context对象
     * @param dip     dip数值
     * @return
     */
    public static int formatDipToPx(Context context, int dip) {
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay()
                .getMetrics(dm);
        //return (int) Math.ceil(dip * dm.density);
        //return dip2px(context,dip);
        Log.e("formatDipToPx", Math.ceil(dip * dm.density)+"_"+dip2px(context,dip)+"_"+ TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dip, context.getResources().getDisplayMetrics()));
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dip, context.getResources().getDisplayMetrics());
    }

    public static double formatDipToPx(Context context, double dip) {
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay()
                .getMetrics(dm);

        Log.e("formatDipToPx", Math.ceil(dip * dm.density)+"_"+dip2px(context,dip)+"_"+ TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dip, context.getResources().getDisplayMetrics()));

//        return dip2px(context,dip);
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dip, context.getResources().getDisplayMetrics());
    }

    /**
     * 把px单位转成dip单位
     *
     * @param context context对象
     * @param px      px数值
     * @return
     */
    public static int formatPxToDip(Context context, int px) {
//        DisplayMetrics dm = new DisplayMetrics();
//        ((Activity) context).getWindowManager().getDefaultDisplay()
//                .getMetrics(dm);
//        return (int) Math.ceil(((px * 160) / dm.densityDpi));
        return px2dip(context,px);
    }

    public static double formatPxToDip(Context context, float px) {
//        DisplayMetrics dm = new DisplayMetrics();
//        ((Activity) context).getWindowManager().getDefaultDisplay()
//                .getMetrics(dm);
//        return Math.ceil(((px * 160) / dm.densityDpi));
        return px2dip(context,px);
    }


    public static int px2dip(Context context, int pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static double px2dip(Context context, double pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return pxValue / scale + 0.5f;
    }

    public static int dip2px(Context context, int dpValue) {
        float density = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * density + 0.5);
    }

    public static double dip2px(Context context, double dpValue) {
        float density = context.getResources().getDisplayMetrics().density;
        return dpValue * density + 0.5;
    }

    public static int getScreenWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    public static int getScreenHeight(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param pxValue
     * DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }


    /**
     * 获取屏幕宽度
     *
     * @param
     * @return
     */
    public static int getWindowWidth(Context context) {
        return  ((Activity) context).getWindowManager().getDefaultDisplay().getWidth();
    }
}
